<template>
  <div class="attraction-detail" :class="{ 'rotating': isRotating }">
    <!-- 开屏动画 -->
    <SplashScreen
      v-if="showSplash"
      @close="handleSplashClose"
    />

    <DraggableBackground
      ref="draggableBackground"
      :background-src="attractionData.backgroundImage"
      :markers="mapMarkers"
      :active-marker-id="activeMarkerId"
      :default-zoom="1.3"
      :min-zoom="1"
      :max-zoom="2"
      @marker-click="handleMarkerClick"
    >
    </DraggableBackground>

    <!-- 标记点详情弹窗 -->
    <MarkerPopup
      :visible="showMarkerPopup"
      :marker-data="selectedMarker"
      @close="closeMarkerPopup"
      @action="handleMarkerAction"
    />
  </div>
</template>

<script>
import DraggableBackground from '@/components/DraggableBackground.vue'
import MarkerPopup from '@/components/MarkerPopup.vue'
import SplashScreen from '@/components/SplashScreen.vue'
import { getAllH5List, getBackH5groundImage } from '@/api'
export default {
  name: 'AttractionDetail',
  components: {
    DraggableBackground,
    MarkerPopup,
    SplashScreen
  },
  data() {
    return {
      showSplash: true,
      isCardExpanded: false,
      showMarkerPopup: false,
      selectedMarker: {},
      activeMarkerId: null,
      screenOrientation: 'portrait', // 记录屏幕方向
      isRotating: false, // 旋转状态标记
      attractionData: {
        name: '建筑',
        backgroundImage:  '',//require("@/assets/imgs/旅游.png"), // 临时使用unsplash的山景图片
        rating: 4.8,
        distance: '距离您 2.5km',
        status: 'open',
        statusText: '正常开放',
        description: '九寨沟位于四川省阿坝藏族羌族自治州九寨沟县境内，是中国第一个以保护自然风景为主要目的的自然保护区。这里有着"童话世界"的美誉，以翠海、叠瀑、彩林、雪峰、藏情、蓝冰"六绝"著称于世。',
        highlights: ['世界自然遗产', '国家5A级景区', '童话世界', '四季皆美'],
        facilities: [
          { icon: '🚌', name: '观光车' },
          { icon: '🍽️', name: '餐厅' },
          { icon: '🛍️', name: '购物' },
          { icon: '📷', name: '拍照点' },
          { icon: '♿', name: '无障碍' },
          { icon: '🚻', name: '洗手间' }
        ],
        openingHours: '08:00 - 18:00（旺季）\n08:30 - 17:30（淡季）',
        ticketPrice: 169,
        priceNote: '成人票（含观光车）'
      },
      mapMarkers: [
        {
          id: 1,
          name: '五花海',
          x: 35,
          y: 25,
          type: 'highlight',
          icon: '🌊',
          showPulse: true,
          description: '九寨沟最著名的海子之一，因湖底的钙华沉积、各种色泽的藻类以及岸边五彩斑斓的林木倒影而得名。',
          image: 'https://images.unsplash.com/photo-1439066615861-d1af74d74000?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
          features: ['最佳拍照点', '四季变色', '清澈见底'],
          openTime: '全天开放',
          rating: 4.9,
          tips: '最佳观赏时间为上午10点到下午3点，光线充足时湖水颜色最为绚烂。',
          actions: [
            { text: '查看路线', type: 'primary' },
            { text: '收藏', type: 'default' }
          ]
        },
        {
          id: 2,
          name: '珍珠滩瀑布',
          x: 60,
          y: 40,
          type: 'viewpoint',
          icon: '💎',
          description: '九寨沟最壮观的瀑布之一，水流从高处倾泻而下，形成珍珠般的水花。',
          image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
          features: ['壮观瀑布', '负氧离子丰富', '彩虹常现'],
          openTime: '08:00 - 18:00',
          rating: 4.8,
          tips: '雨后观赏效果最佳，容易看到彩虹。注意防滑。',
          actions: [
            { text: '导航前往', type: 'primary' },
            { text: '分享', type: 'default' }
          ]
        },
        {
          id: 3,
          name: '诺日朗餐厅',
          x: 45,
          y: 60,
          type: 'restaurant',
          icon: '🍽️',
          description: '景区内主要的餐饮服务点，提供藏式和川式美食。',
          features: ['藏式美食', '川菜', '素食选择'],
          openTime: '11:00 - 14:00, 17:00 - 20:00',
          rating: 4.2,
          tips: '建议提前预订，用餐高峰期人较多。',
          actions: [
            { text: '在线预订', type: 'primary' },
            { text: '查看菜单', type: 'default' }
          ]
        },
        {
          id: 4,
          name: '观光车站',
          x: 25,
          y: 75,
          type: 'facility',
          icon: '🚌',
          description: '景区观光车停靠站，可乘坐观光车前往各个景点。',
          features: ['观光车服务', '休息区', '问询处'],
          openTime: '07:30 - 18:30',
          tips: '观光车每15分钟一班，建议查看时刻表。',
          actions: [
            { text: '查看班次', type: 'primary' }
          ]
        },
        {
          id: 5,
          name: '镜海',
          x: 70,
          y: 20,
          type: 'highlight',
          icon: '🪞',
          showPulse: true,
          description: '以完美的倒影闻名，湖面如镜，倒映着周围的雪山和森林。',
          image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
          features: ['完美倒影', '摄影圣地', '宁静致远'],
          openTime: '全天开放',
          rating: 4.7,
          tips: '清晨无风时倒影效果最佳，是摄影的黄金时间。',
          actions: [
            { text: '设为目的地', type: 'primary' },
            { text: '收藏', type: 'default' }
          ]
        },
        {
          id: 6,
          name: '游客服务中心',
          x: 15,
          y: 85,
          type: 'facility',
          icon: 'ℹ️',
          description: '提供游客咨询、失物招领、医疗救助等服务。',
          features: ['游客咨询', '医疗救助', '失物招领', '轮椅租借'],
          openTime: '07:00 - 19:00',
          tips: '如有紧急情况或需要帮助，请及时联系服务中心。',
          actions: [
            { text: '联系客服', type: 'primary' }
          ]
        }
      ]
    }
  },
  mounted() {
    this.initOrientationListener()
    this.updateOrientation()
  },
  beforeDestroy() {
    this.removeOrientationListener()
  },
  methods: {
    async getBac() {
      const res = await getBackH5groundImage('h5_background_image')
      console.log("背景图", res)
      if(res.code == 200) {
        this.attractionData.backgroundImage = res.data.configValues || ''
      }
    },
    async fetchLists() {
      const res = await getAllH5List('h5_background_image')
      console.log("标注", res)
      this.mapMarkers = res.data.map(el => {
        return {
          ...el,
          name: el.buildingName,
          x: el.h5Left - 0,
          y: el.h5Top - 0,
          type: 'highlight',
          showPulse: true,
          description: el.buildingIntroduction,
          image: el.buildingImgUrl,
          // actions: [
          //   { text: '查看路线', type: 'primary' },
          //   { text: '收藏', type: 'default' }
          // ]
        }
      })
    },
    handleSplashClose() {
      this.showSplash = false
      // 可以在这里添加一些初始化逻辑
      console.log('开屏动画关闭，开始体验')
    },
    goBack() {
      this.$router.go(-1)
    },
    toggleCard() {
      this.isCardExpanded = !this.isCardExpanded
    },
    resetDrag() {
      // 重置拖拽状态
      this.$refs.draggableBackground?.resetDragState?.()
    },
    handleMarkerClick(marker) {
      console.log('AttractionDetail: 标记点被点击', marker)
      this.selectedMarker = marker
      this.activeMarkerId = marker.id
      this.showMarkerPopup = true
    },
    closeMarkerPopup() {
      this.showMarkerPopup = false
      this.activeMarkerId = null
      this.selectedMarker = {}
    },
    handleMarkerAction(action) {
      console.log('标记点操作:', action)
      // 这里可以根据不同的action类型执行不同的操作
      switch(action.text) {
        case '查看路线':
        case '导航前往':
        case '设为目的地':
          this.showRoute(this.selectedMarker)
          break
        case '收藏':
          this.addToFavorites(this.selectedMarker)
          break
        case '在线预订':
          this.makeReservation(this.selectedMarker)
          break
        case '查看菜单':
          this.showMenu(this.selectedMarker)
          break
        case '查看班次':
          this.showSchedule(this.selectedMarker)
          break
        case '联系客服':
          this.contactService()
          break
        default:
          console.log('未知操作:', action)
      }
    },
    showRoute(marker) {
      alert(`正在为您规划前往 ${marker.name} 的路线...`)
    },
    addToFavorites(marker) {
      alert(`已将 ${marker.name} 添加到收藏夹`)
    },
    makeReservation(marker) {
      alert(`正在跳转到 ${marker.name} 的预订页面...`)
    },
    showMenu(marker) {
      alert(`正在查看 ${marker.name} 的菜单...`)
    },
    showSchedule() {
      alert(`正在查看观光车班次信息...`)
    },
    contactService() {
      alert(`正在连接客服...`)
    },

    // 屏幕旋转监听相关方法
    initOrientationListener() {
      // 监听屏幕方向变化
      if (screen.orientation) {
        screen.orientation.addEventListener('change', this.handleOrientationChange)
      } else {
        // 兼容旧版浏览器
        window.addEventListener('orientationchange', this.handleOrientationChange)
      }

      // 监听窗口大小变化（作为备用方案）
      window.addEventListener('resize', this.handleResize)
    },

    removeOrientationListener() {
      if (screen.orientation) {
        screen.orientation.removeEventListener('change', this.handleOrientationChange)
      } else {
        window.removeEventListener('orientationchange', this.handleOrientationChange)
      }
      window.removeEventListener('resize', this.handleResize)
    },

    updateOrientation() {
      const width = window.innerWidth
      const height = window.innerHeight
      this.screenOrientation = width > height ? 'landscape' : 'portrait'
    },

    handleOrientationChange() {
      console.log('屏幕方向发生变化')
      this.isRotating = true

      // 延迟处理，等待旋转动画完成
      setTimeout(() => {
        this.updateOrientation()
        this.refreshContent()
        this.isRotating = false
        console.log('屏幕旋转处理完成，当前方向:', this.screenOrientation)
      }, 300)
    },

    handleResize() {
      // 防抖处理
      clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(() => {
        const oldOrientation = this.screenOrientation
        this.updateOrientation()

        // 只有方向真正改变时才处理
        if (oldOrientation !== this.screenOrientation) {
          console.log('窗口大小变化导致方向改变:', oldOrientation, '->', this.screenOrientation)
          this.refreshContent()
        }
      }, 150)
    },

    refreshContent() {
      // 刷新地图组件
      if (this.$refs.draggableBackground) {
        this.$nextTick(() => {
          // 重新初始化地图尺寸
          this.$refs.draggableBackground.handleResize?.()

          // 延迟重新计算布局
          setTimeout(() => {
            this.$refs.draggableBackground.centerMap?.()
            console.log('地图组件已重新渲染')
          }, 100)
        })
      }

      // 强制重新渲染组件
      this.$forceUpdate()

      // 触发自定义事件，通知其他组件
      this.$emit('orientation-changed', {
        orientation: this.screenOrientation,
        width: window.innerWidth,
        height: window.innerHeight
      })
    }
  },
  created(){
    this.getBac()
    this.fetchLists()
  }
}
</script>

<style lang="scss" scoped>
.attraction-detail {
  height: 100vh;
  overflow: hidden;
  transition: all 0.3s ease;

  &.rotating {
    opacity: 0.8;

    &::after {
      content: '正在适配屏幕...';
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 12px 24px;
      border-radius: 20px;
      font-size: 14px;
      z-index: 9998;
      backdrop-filter: blur(10px);
    }
  }
}

.top-nav {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: linear-gradient(180deg, rgba(0,0,0,0.5) 0%, transparent 100%);
  z-index: 100;
  
  .back-btn, .share-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: rgba(0,0,0,0.3);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      background: rgba(0,0,0,0.5);
    }
  }
  
  .nav-title {
    color: white;
    font-size: 18px;
    font-weight: 600;
    text-shadow: 0 1px 3px rgba(0,0,0,0.5);
  }
}

.bottom-card {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-radius: 20px 20px 0 0;
  min-height: 200px;
  max-height: 80vh;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  cursor: pointer;
  box-shadow: 0 -10px 30px rgba(0,0,0,0.1);
  
  &.expanded {
    min-height: 60vh;
  }
  
  .card-handle {
    width: 40px;
    height: 4px;
    background: #ddd;
    border-radius: 2px;
    margin: 12px auto 20px;
  }
  
  .card-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 0 20px 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .attraction-info {
      flex: 1;
      
      .attraction-name {
        font-size: 24px;
        font-weight: 700;
        color: #333;
        margin: 0 0 8px 0;
      }
      
      .attraction-meta {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .rating {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #333;
          font-weight: 600;
        }
        
        .distance {
          color: #666;
          font-size: 14px;
        }
        
        .status {
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 600;
          
          &.open {
            background: #e8f5e8;
            color: #2d7d32;
          }
        }
      }
    }
    
    .expand-icon {
      transition: transform 0.3s ease;
      
      &.rotated {
        transform: rotate(180deg);
      }
    }
  }
  
  .card-content {
    padding: 20px;
    max-height: 50vh;
    overflow-y: auto;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin: 0 0 12px 0;
    }
    
    .description {
      margin-bottom: 24px;
      
      p {
        color: #666;
        line-height: 1.6;
        margin: 0;
      }
    }
    
    .highlights {
      margin-bottom: 24px;
      
      .highlight-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .tag {
          padding: 6px 12px;
          background: #f0f8ff;
          color: #1976d2;
          border-radius: 16px;
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
    
    .facilities {
      margin-bottom: 24px;
      
      .facility-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        
        .facility-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          
          .facility-icon {
            font-size: 24px;
            margin-bottom: 4px;
          }
          
          .facility-name {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
    
    .opening-hours, .ticket-info {
      margin-bottom: 24px;
      
      p {
        color: #666;
        line-height: 1.6;
        margin: 0;
        white-space: pre-line;
      }
      
      .ticket-price {
        display: flex;
        align-items: baseline;
        gap: 8px;
        
        .price {
          font-size: 24px;
          font-weight: 700;
          color: #e53e3e;
        }
        
        .price-note {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid #f0f0f0;
    
    .btn {
      flex: 1;
      height: 48px;
      border: none;
      border-radius: 24px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.btn-secondary {
        background: #f5f5f5;
        color: #333;
        
        &:hover {
          background: #e0e0e0;
        }
      }
      
      &.btn-primary {
        background: #1976d2;
        color: white;
        
        &:hover {
          background: #1565c0;
        }
      }
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .top-nav {
    height: 50px;
    padding: 0 16px;
    
    .nav-title {
      font-size: 16px;
    }
  }
  
  .bottom-card {
    .card-header {
      padding: 0 16px 16px;
      
      .attraction-name {
        font-size: 20px;
      }
    }
    
    .card-content {
      padding: 16px;
      
      .facilities .facility-list {
        grid-template-columns: repeat(2, 1fr);
      }
    }
    
    .action-buttons {
      padding: 16px;
    }
  }
}
</style>
